import { Component } from 'react';
import Taro, { getCurrentInstance } from '@tarojs/taro';
import { View, Text, PickerView, PickerViewColumn, Image } from '@tarojs/components'
import { AtCalendar, AtButton } from 'taro-ui'
import { getAppointmentTime } from '@/api/order/booking'
import dayjs from 'dayjs'
import Qualifying from './Qualifying'
import { debounce } from '@/utils'
import { staticUrl } from '@/utils'
import { updateBooking } from '@/api/order'
import './index.scss'

const timeLineImg = staticUrl('/img/order/time-line.png')

interface State{
    serverTime: any
    appointmentInfo: any
    currHour: string
    currDate: any
    validDates: any
    select?: Array<number>
}

export default class Index extends Component<any, State> {
    $instance = getCurrentInstance();
    constructor (props) {
        super(props)
        this.state = {
            serverTime: null,
            appointmentInfo: null,
            currHour: '',
            currDate: 0,
            validDates: []
        }
    }

    state: State

    UNSAFE_componentWillMount() { }
    componentDidMount() {
        const { applyTime }: any = this.$instance.router.params
        let params: any = {}
        if (applyTime) {
            params.date = dayjs.unix(applyTime).format('YYYY-MM-DD')
        }
        this.getAppointmentTime(params)
    }
    UNSAFE_componentWillReceiveProps(nextProps, nextContext) { }
    componentWillUnmount() { }
    config = {
        navigationBarTitleText: '预约时间',
        // disableScroll: true
    }
    componentDidShow() { }
    componentDidHide() { }
    componentDidCatchError() { }
    componentDidNotFound() { }
    private select: Array<number> = [0, 0]
    private isBooking: boolean = false
    // 确定预约
    confirmBooking() {
        if (this.isBooking) return
        const { from } = this.$instance.router.params
        this.isBooking = true
        const { appointmentInfo } = this.state
        const serviceStartAtList: any = appointmentInfo.serviceStartAtList[this.select[0]]
        const time = serviceStartAtList.items[this.select[1]].startAt
        if (from === 'annual') {
            Taro.setStorageSync('BOOKING_TIME', time)
            Taro.navigateBack({
                delta: 1
            })
            return
        }
        this.updateBooking(time)
    }

    updateBooking(time) {
        const { orderNumber } = this.$instance.router.params
        updateBooking({
            orderNumber,
            time
        }).then(res => {
            Taro.showToast({
                icon: 'none',
                title: '预约成功'
            })
            this.isBooking = false
            this.checkedBookingNavigate()

        }).catch(e => {
            this.isBooking = false
        })
    }

    checkedBookingNavigate() {
        Taro.navigateBack()
    }

    // 预约时间
    getAppointmentTime(params: any = {}) {
        let { order, applyTime } = this.$instance.router.params
        order = JSON.parse(order)
        const goodsData = JSON.stringify(order.map(goods => {
            const { goodsId, goodsSkuId, number, type: itemType } = goods
            return {
                goodsId,
                goodsSkuId,
                number,
                itemType
            }
        }))
        params = {
            ...params,
            goodsData
        }
        getAppointmentTime(params).then(res => {
            const { serverTime } = this.state
            const data = res.data.data
            const size = data.serviceStartAtList.length
            let setData: any = {
                appointmentInfo: data,
                currHour: size ? data.serviceStartAtList[0].hourLabel : '',
                validDates: {
                    start: dayjs(data.fromDate).valueOf(),
                    end: dayjs(data.toDate).valueOf()
                }
            }

            if (!serverTime) {
                setData.serverTime =  new Date(res.header.Date).getTime()
                setData.currDate = applyTime ? dayjs.unix(applyTime).valueOf() : setData.serverTime
            }
            if (params.date) {
                setData.currDate = dayjs(params.date).valueOf()
            }
            this.setState(setData)
        })
    }

    // 选择时间
    changePicker(e) {
        const { appointmentInfo } = this.state
        const { value } = e.detail
        const hourIndex = value[0]
        const hourLabel = appointmentInfo.serviceStartAtList[hourIndex].hourLabel
        // if (currHour === hourLabel) return
        this.select = value
        // console.log(this.select, value)
        this.setState({
            currHour: hourLabel
        })

    }
    // 选择日期
    changeDay = debounce(async (e) => {
        const { value } = e
        await this.getAppointmentTime({
            date: value.start
        })
    }, 500)

    render() {
        const { currDate, serverTime, appointmentInfo, validDates } = this.state
        let hours: any = []
        // let minutes = []
        if (appointmentInfo) {
            hours = appointmentInfo.serviceStartAtList
        }
        return appointmentInfo && (
            <View className='booking-main'>
                <View className='calendar'>
                    <AtCalendar currentDate={currDate} onSelectDate={(e) => this.changeDay(e)} minDate={validDates.start} maxDate={validDates.end} />
                </View>
                <View className='booking-main-view'>
                    <View className='booking-line'>
                        <View className='status-list'>
                            <View className='li ym'>约满</View>
                            <View className='li fm'>繁忙</View>
                            <View className='li kx'>空闲</View>
                        </View>
                        <View className='cvs canvas-draw'>
                            <Qualifying selectDate={currDate} info={appointmentInfo} />
                        </View>
                        <View className='time-line'><Image mode='widthFix' className='img' src={timeLineImg}></Image></View>
                    </View>
                    <View className='picker-time'>
                        <View className='title'>选择到店时间 <Text className='tips-time'>（预计施工时长：{appointmentInfo.orderConsume}分钟）</Text></View>
                        {
                            hours.length && (<PickerView indicatorClass='indicator-class' indicator-style='height: 65rpx' className='picker-view' value={this.select} onChange={this.changePicker}>
                                                <PickerViewColumn className='lf'>
                                                    {
                                                        hours.map((hour: any) => {
                                                            return <View key={hour.hourLabel} className='picker-time-block'>{hour.hourLabel}</View>
                                                        })
                                                    }
                                                </PickerViewColumn>
                                                <PickerViewColumn className='rg'>
                                                    {
                                                        hours[this.select[0]].items.map((minute: any) => {
                                                            return <View key={minute.startAt} className='picker-time-block'>{minute.minuteLabel}</View>
                                                        })
                                                    }
                                                </PickerViewColumn>
                                            </PickerView>)
                        }
                    </View>
                </View>
                {
                    hours.length && <View className='confirm-btn'><AtButton onClick={this.confirmBooking.bind(this)} type='primary'>确定</AtButton></View>
                }
            </View>
        )
    }
}
